package com.suxin.plugin.intergration.factory.process.pip.bean;

import com.suxin.plugin.intergration.factory.PluginRegistryInfo;
import com.suxin.plugin.intergration.factory.SpringBeanRegister;
import com.suxin.plugin.intergration.factory.process.pip.PluginPipeProcessor;
import com.suxin.plugin.intergration.factory.process.pip.classs.group.ComponentGroup;
import com.suxin.plugin.intergration.factory.process.pip.classs.group.ConfigurationGroup;
import com.suxin.plugin.intergration.factory.process.pip.classs.group.ControllerGroup;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Tang
 * @classname BasicBeanProcessor
 * @description [ 注册bean ]
 * @date 2022/7/22 23:17
 */
public class BasicBeanProcessor implements PluginPipeProcessor {

    private final ApplicationContext applicationContext;
    private final SpringBeanRegister springBeanRegister;

    public BasicBeanProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        this.springBeanRegister = new SpringBeanRegister(applicationContext);
    }

    @Override
    public void initialize() throws Exception {

    }

    @Override
    public void registry(PluginRegistryInfo pluginRegistryInfo) throws Exception {
        List<String> beanNames = new ArrayList<>();
        Map<String, List<Class<?>>> groupClass = pluginRegistryInfo.getGroupClass();
        // 注册bean
        registry(pluginRegistryInfo,groupClass.get(ComponentGroup.GROUP_ID),beanNames);
        registry(pluginRegistryInfo,groupClass.get(ConfigurationGroup.GROUP_ID),beanNames);
        registry(pluginRegistryInfo,groupClass.get(ControllerGroup.GROUP_ID),beanNames);
    }

    private void registry(PluginRegistryInfo pluginRegistryInfo, List<Class<?>> classList, List<String> beanNames) {
        if (classList == null || classList.isEmpty()) {
            return;
        }
        for (Class<?> aClass : classList) {
            if (aClass == null) {
                continue;
            }
            // todo aop 问题
            String beanName = this.springBeanRegister.register(pluginRegistryInfo.getPluginId(), aClass);
            beanNames.add(beanName);
        }
    }

    @Override
    public void unRegistry(PluginRegistryInfo pluginRegistryInfo) {

    }
}
